﻿using UnityEngine;
using System;

[Serializable]
public enum DriveType
{
	RearWheelDrive,
	FrontWheelDrive,
	AllWheelDrive
}

public class WheelDrive : MonoBehaviour
{
    [Tooltip("车轮的最大转向角")]
	public float maxAngle = 30f;
    [Tooltip("驱动轮最大扭矩")]
	public float maxTorque = 300f;
    [Tooltip("矩适用于驱动轮的最大制动扭矩")]
	public float brakeTorque = 30000f;
    [Tooltip("如果您需要视觉车轮自动连接，请在这里拖动车轮形状。")]
	public GameObject wheelShape;

    [Tooltip("当物理引擎可以使用不同数量的子步骤时车辆的速度。（以m/s为单位）")]
	public float criticalSpeed = 5f;
    [Tooltip("当速度高于临界值时，模拟子步骤。")]
	public int stepsBelow = 5;
    [Tooltip("当速度低于临界值时，模拟子步骤。")]
	public int stepsAbove = 1;

    [Tooltip("车辆的驱动类型：后轮驱动、前轮驱动或全轮驱动。")]
	public DriveType driveType;

    private WheelCollider[] m_Wheels;

    // 找到所有的车轮
	void Start()
	{
		m_Wheels = GetComponentsInChildren<WheelCollider>();

		for (int i = 0; i < m_Wheels.Length; ++i) 
		{
			var wheel = m_Wheels [i];

			// Create wheel shapes only when needed.
			if (wheelShape != null)
			{
				var ws = Instantiate (wheelShape);
				ws.transform.parent = wheel.transform;
			}
		}
	}

    //这是一个非常简单的更新轮子的方法。
    //我们模拟一个后轮驱动汽车，假设汽车在局部零点是完全对称的。
    //这有助于我们弄清哪些轮子是前轮，哪些是后轮。
	void Update()
	{
		m_Wheels[0].ConfigureVehicleSubsteps(criticalSpeed, stepsBelow, stepsAbove);

		float angle = maxAngle * Input.GetAxis("Horizontal");
		float torque = maxTorque * Input.GetAxis("Vertical");

		float handBrake = Input.GetKey(KeyCode.X) ? brakeTorque : 0;

		foreach (WheelCollider wheel in m_Wheels)
		{
			// A simple car where front wheels steer while rear ones drive.
			if (wheel.transform.localPosition.z > 0)
				wheel.steerAngle = angle;

			if (wheel.transform.localPosition.z < 0)
			{
				wheel.brakeTorque = handBrake;
			}

			if (wheel.transform.localPosition.z < 0 && driveType != DriveType.FrontWheelDrive)
			{
				wheel.motorTorque = torque;
			}

			if (wheel.transform.localPosition.z >= 0 && driveType != DriveType.RearWheelDrive)
			{
				wheel.motorTorque = torque;
			}

			// Update visual wheels if any.
			if (wheelShape) 
			{
				Quaternion q;
				Vector3 p;
				wheel.GetWorldPose (out p, out q);

				// Assume that the only child of the wheelcollider is the wheel shape.
				Transform shapeTransform = wheel.transform.GetChild (0);
				shapeTransform.position = p;
				shapeTransform.rotation = q;
			}
		}
	}
}
